package com.lingxu.base.common.exception;

import com.lingxu.base.common.api.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

/**
 * @Title: GlobalExceptionHandler
 * @Package: com.lingxu.base.common.exception
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2021/4/14 10:37
 * @Description:
 * @Version: 1.0.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result ExceptionHandler(Exception e){
        e.printStackTrace();//打印异常位置及异常原因
        //SQL查询出null异常
        if(e instanceof NullCollectionException){
            e.getStackTrace().toString();
            return new Result().error500(e.getMessage());
            //sql异常
        }else if(e instanceof InsertSqlException){
            return new Result().error500(e.getMessage());
            //空参数异常
        }else if(e instanceof NullParamException){
            return new Result().error500(e.getMessage());
            //Bean必填项校验
        }else if(e instanceof BindException){
            return new Result().error500(((BindException) e).getBindingResult().getFieldError().getDefaultMessage());
            //请求方法错误异常
        }else if(e instanceof HttpRequestMethodNotSupportedException){
            return Result.error(400,"请求方式错误 [" + ((HttpRequestMethodNotSupportedException) e).getMethod() + "]");
            //单个参数校验
        }else if(e instanceof ConstraintViolationException){
            return Result.error(403,"请求参数错误：" + e.getMessage());
        }else if(e instanceof HttpException){
            return new Result().error500(e.getMessage());
        }
        logger.error("发生业务异常！原因是：{}",e.getMessage());
        return new Result().error500("未知异常");
    }
}
